package dp.metel.likeme.versiontracking.service;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;



@Service("VersionTrackingService")
public class VersionTrackingServiceImpl implements VersionTrackingService {

	/**
	 * logger for MemoManager.
	 */
	private static final Logger Logger = LoggerFactory.getLogger(VersionTrackingServiceImpl.class);
	
	
	
	@Override	
	public Response getVersion()
			throws Exception {
		
		String jarPath = getClass().getClassLoader().getResource("/").getPath()+"../../META-INF/" +"MANIFEST.MF";
		
		BuildVersion version = new BuildVersion();
		//version.setBuildDate(getBuildVersion(jarName,"Build-Date"));
		//version.setRevision(getBuildVersion(jarName,"Revision-Number"));
		
		Logger.debug(jarPath);
		
		Manifest manifest = null;
		
		try {
			JarFile jarfile = new JarFile(jarPath);
			manifest = jarfile.getManifest();
		} catch (Exception e) {
			Logger.error(e.getMessage());
			
		}
		if(manifest == null) {
			try {
				InputStream is = new FileInputStream(jarPath);
				manifest = new Manifest(is);
			} catch (Exception e) {
				Logger.error(e.getMessage());
				
			}
		}
		if(manifest != null) {
		 // Get the main attributes in the manifest
		    Attributes attrs = (Attributes)manifest.getMainAttributes(); 
		    version.setBuildDate(attrs.getValue("Build-Date"));
		    version.setRevision(attrs.getValue("Revision-Number"));		    
		}
				
		return Response.ok(version).build();
	}

	
	

}
